package edu.beyond.employment.talent.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.beyond.employment.commom.Constant;
import edu.beyond.employment.commom.PageModel;
import edu.beyond.employment.commom.util.AppUtil;
import edu.beyond.employment.company.dao.ApplicationDao;
import edu.beyond.employment.company.entity.ApplicationEntity;
import edu.beyond.employment.talent.dao.ResumeDao;
import edu.beyond.employment.talent.dao.TalentDao;
import edu.beyond.employment.talent.entity.ResumeEntity;
import edu.beyond.employment.talent.entity.TalentEntity;

/**
 * 求职者Servlet
 */
public class TalentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TalentDao talentDao = new TalentDao();
	private ResumeDao resumeDao = new ResumeDao();
	private ApplicationDao applicationDao = new ApplicationDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 解决乱码问题
		request.setCharacterEncoding("UTF-8");
		// 获取前台传来的参数
		String command = request.getParameter("command");
		if ("register".equals(command)) {
			register(request, response);
		} else if ("login".equals(command)) {
			login(request, response);
		} else if ("get".equals(command)) {
			info(request, response);
		} else if ("logout".equals(command)) {
			logout(request, response);
		} else if ("main".equals(command)) {
			main(request, response);
		} else if ("get".equals(command)) {
			get(request, response);
		}

		else {
			throw new IllegalStateException("请求非法~");
		}

	}

	/**
	 * 求职者注册Servlet
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获取前台传来的参数
		request.setCharacterEncoding("UTF-8");
		String code = request.getParameter("code");
		String password = request.getParameter("passwd");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		int age = Integer.parseInt(request.getParameter("age"));
		int gender = Integer.parseInt(request.getParameter("gender"));
		StringBuilder sb = new StringBuilder();
		String[] hobbies = request.getParameterValues("hobby");
		// for (String string : hobbies) {
		// System.out.println(string);
		// }
		for (int i = 0; i < hobbies.length; i++) {
			if (i == hobbies.length - 1) {
				sb.append(hobbies[i]);
			} else {
				sb.append(hobbies[i] + "|");
			}
		}
		// 调用业务逻辑
		TalentEntity talentEntity = new TalentEntity();
		talentEntity.setCode(code);
		talentEntity.setPassword(password);
		talentEntity.setName(name);
		talentEntity.setPhone(phone);
		talentEntity.setEmail(email);
		talentEntity.setAge(age);
		talentEntity.setGender(gender);
		talentEntity.setHobby(sb.toString());
		new TalentDao().register(talentEntity);
		// 转向页面
		request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);
	}

	/**
	 * 求职者登录Servlet
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		// 获取页面传来的参数
		String code = request.getParameter("code");
		String password = request.getParameter("passwd");
		// 获取表单验证码
		String validateCode = request.getParameter("validate");
		// session里存放的验证码
		String sessionCode = (String) request.getSession().getAttribute("rand");
		if (!validateCode.equals(sessionCode)) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "验证码输入错误 ！");
			request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);
		}
		// 调用业务逻辑
		TalentEntity talent = talentDao.login(code, password);

		// 转向页面(做判断)
		if (talent == null) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "用户名或密码错误");
			request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);

		} else {
			// 如果有此求职者就去查询求职者的简历信息，并放到request里面，方便在页面上显示
			List<ResumeEntity> resumeList = resumeDao.list(talent.getId());
			request.setAttribute("resumeList", resumeList);

			// 使用reuqes传递talent对象，如果要保证在多个页面共享值，需要逐步传递
			// request.setAttribute("talent", talent);
			// 使用session传递talent对象，在其生命期间内 ，可保证在整个项目共享值，这是登录时共享值的通常做法！
			request.getSession().setAttribute("talent", talent);
			// 重定向 -> 优点：地址上不会显示此次Servlet的请求地址！，缺点：不可以携带参数
			// response.sendRedirect("static/talent/talent-home.jsp");
			// request.getRequestDispatcher("static/talent/talent-home.jsp").forward(request,
			// response);
			response.sendRedirect("TalentServlet?command=main");
		}

	}

	/**
	 * 求职者的信息修改
	 */

	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取参数
		request.setCharacterEncoding("UTF-8");
		int id = Integer.parseInt(request.getParameter("id"));
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		int age = Integer.parseInt(request.getParameter("age"));
		int gender = Integer.parseInt(request.getParameter("gender"));
		String[] hobbies = request.getParameterValues("hobby");
		// 调用业务逻辑
		TalentEntity talent = new TalentEntity();
		StringBuilder sb = new StringBuilder();
		talent.setId(id);
		talent.setPassword(password);
		talent.setName(name);
		talent.setPhone(phone);
		talent.setEmail(email);
		talent.setAge(age);
		talent.setGender(gender);
		talent.setHobby(sb.toString());
		int row = new TalentDao().get(talent);
		if (row == 1) {
			request.setAttribute("success", "个人信息修改成功！");

		} else {
			request.setAttribute("fail", "个人信息修改失败！");
		}

		int talentId = AppUtil.getTalentId(request, response);
		List<ResumeEntity> resumeList = resumeDao.list(talentId);
		request.setAttribute("resumeList", resumeList);
		// List<ApplicationEntity> applicationList =
		// applicationDao.list(talentId);
		// request.setAttribute("applicationList", applicationList);
		int pageNo = Constant.DEFAULT_PAGE_NO;
		// 非登录操作
		String pageNoStr = request.getParameter("pageNo");
		if (pageNoStr != null) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		// 申请信息
		PageModel<ApplicationEntity> pageModel = applicationDao.listTalentApplyByPage(talentId, pageNo,
				Constant.DEFAULT_PAGE_SIZE);
		// 转向页面
		request.setAttribute("talent", talent);
		request.getRequestDispatcher("view/talent/talent-home.jsp").forward(request, response);

	}

	/**
	 * 求职者个人资料管理
	 */
	private void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		// 获取参数
		int id = Integer.parseInt(request.getParameter("id"));
		// 调用业务逻辑
		TalentEntity talent = talentDao.info(id);
		// 转向页面
		request.setAttribute("talent", talent);
		request.getRequestDispatcher("view/talent/talent-info.jsp").forward(request, response);

	}

	/**
	 * 到主页时的查询
	 */

	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// // 获取参数
		// int id = AppUtil.getTalentId(request, response);
		// // 调用业务逻辑
		// List<ResumeEntity> resumeList = resumeDao.list(id);
		// request.setAttribute("resumeList", resumeList);
		// // 如果有此求职者就去查询求职者的求职信息，并放到request里面，方便在页面上显示
		// List<ApplicationEntity> applicationList = applicationDao.list(id);
		// request.setAttribute("applicationList", applicationList);
		// // 转向页面
		// request.getRequestDispatcher("static/talent/talent-home.jsp").forward(request,
		// response);

		String rowStr = request.getParameter("row");
		// 非登录操作
		if (rowStr != null) {
			int row = Integer.parseInt(rowStr);
			if (row == 1) {
				request.setAttribute("success", "操作成功！");
			} else {
				request.setAttribute("error", "操作失败！");
			}
		}

		// 转向
		request.getRequestDispatcher("ApplicationServlet?command=listTalentApplyByPage").forward(request, response);

	}

	/**
	 * logout注销
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 获取页面传来的参数
		// 调用业务逻辑
		request.getSession().invalidate();
		// 转向页面
		// 转发优点：可以携带参数 缺点：地址上显示此次servlet的请求地址，用户可以重复提交
		// request.getRequestDispatcher("static/talent/talent-login.jsp").forward(request,
		// response);
		// 重定向优点：址上显示此次servlet的请求地址，用户可以重复提交 ；缺点：不可以携带参数
		response.sendRedirect("view/talent/talent-login.jsp");
	}

}
